package com.jianshuge.app.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;
import com.jianshuge.app.adapter.ListViewBookshelfAdapter;
import com.jianshuge.app.bean.Bookshelf;
import com.jianshuge.app.bean.BookshelfList;

import com.jianshuge.app.common.StringUtils;
import com.jianshuge.app.common.UIHelper;
import com.jianshuge.app.widget.PullToRefreshListView;

public class NewBook extends BaseActivity {
	
	private ImageView mBack;
	private ProgressBar mProgressbar;

	////////////////////////////////////////////////////
	private PullToRefreshListView mLvNewBook;
	private ListViewBookshelfAdapter lvNewBookAdapter;
	private List<Bookshelf> lvNewBookData = new ArrayList<Bookshelf>();
	
	private View lvNewBook_footer;
	private TextView lvNewBook_foot_more;
	private ProgressBar lvNewBook_foot_progress;
	
    private Handler mNewBookHandler;
    private int lvNewBookSumData;
    ////////////////////////////////////////////////////////
    
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_book);
        
        this.initView();
        this.initData();   
    }
    
    /**
     * 头部加载展示
     * @param type
     */
    private void headButtonSwitch(int type) {
    	switch (type) {
    	case DATA_LOAD_ING:
			mProgressbar.setVisibility(View.VISIBLE);
			break;
		case DATA_LOAD_COMPLETE:
			mProgressbar.setVisibility(View.GONE);
			break;
		}
    }
    
    //初始化视图控件
    private void initView()
    {
    	mBack = (ImageView)findViewById(R.id.new_book_back);
    	mProgressbar = (ProgressBar)findViewById(R.id.new_book_head_progress);    	
    	mBack.setOnClickListener(UIHelper.finish(this));
    	
    	lvNewBookAdapter = new ListViewBookshelfAdapter(this, lvNewBookData, R.layout.bookshelf_listitem);
    	lvNewBook_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvNewBook_foot_more = (TextView) lvNewBook_footer.findViewById(R.id.listview_foot_more);
    	lvNewBook_foot_progress = (ProgressBar) lvNewBook_footer.findViewById(R.id.listview_foot_progress);
		
    	mLvNewBook = (PullToRefreshListView) findViewById(R.id.frame_listview_new_book);
    	mLvNewBook.addFooterView(lvNewBook_footer);// 添加底部视图 必须在setAdapter前
    	mLvNewBook.setAdapter(lvNewBookAdapter);
		
    	mLvNewBook.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						// 点击头部、底部栏无效
						if (position == 0 || view == lvNewBook_footer)
							return;

						Bookshelf bookshelf = null;
						// 判断是否是TextView
						if (view instanceof TextView) {
							bookshelf = (Bookshelf) view.getTag();
						} else {
							TextView tv = (TextView) view.findViewById(R.id.bookshelf_listitem_title);
							bookshelf = (Bookshelf) tv.getTag();
						}
						if (bookshelf == null)
							return;

						// 跳转到问答详情
					//	UIHelper.showBooklistDetail(view.getContext(), bookshelf.getId() );
					}
		});
		
    	mLvNewBook.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				mLvNewBook.onScrollStateChanged(view, scrollState);

				// 数据为空--不用继续下面代码了
				if (lvNewBookData.isEmpty())
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvNewBook_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(mLvNewBook.getTag());
				if (scrollEnd && lvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					mLvNewBook.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvNewBook_foot_more.setText(R.string.load_ing);
					lvNewBook_foot_progress.setVisibility(View.VISIBLE);
					
					// 当前pageIndex
					int pageIndex = lvNewBookSumData / AppContext.PAGE_SIZE;
					loadLvNewBookData(1, pageIndex, mNewBookHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
							
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {	
				mLvNewBook.onScroll(view, firstVisibleItem, visibleItemCount,totalItemCount);			
			}
		});
		
    	mLvNewBook.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			public void onRefresh() {
				loadLvNewBookData(1, 1, mNewBookHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
			}
		});
    	
    }
    
    //初始化控件数据
    private void initData()
    {
    	mNewBookHandler = new Handler() {
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE);

				if(msg.what >= 0){						
					BookshelfList list = (BookshelfList)msg.obj;

					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvNewBookSumData = msg.what;
						lvNewBookData.clear();//先清除原有数据
						lvNewBookData.addAll(list.getBookshelfList());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						lvNewBookSumData += msg.what;
						if(lvNewBookData.size() > 0){
							for(Bookshelf bookshelf1 : list.getBookshelfList()){
								boolean b = false;
								for(Bookshelf bookshelf2 : lvNewBookData){
									if(bookshelf1.getId() == bookshelf2.getId()){
										b = true;
										break;
									}
								}
								if(!b) lvNewBookData.add(bookshelf1);
							}
						}else{
							lvNewBookData.addAll(list.getBookshelfList());
						}
						break;
					}	
					
					if(msg.what < 10){
						mLvNewBook.setTag(UIHelper.LISTVIEW_DATA_FULL);
						lvNewBookAdapter.notifyDataSetChanged();
						lvNewBook_foot_more.setText(R.string.load_full);
					}else if(msg.what == 10){					
						mLvNewBook.setTag(UIHelper.LISTVIEW_DATA_MORE);
						lvNewBookAdapter.notifyDataSetChanged();
						lvNewBook_foot_more.setText(R.string.load_more);
					}
				}
				else if(msg.what == -1){
					//有异常--显示加载出错 & 弹出错误消息
					mLvNewBook.setTag(UIHelper.LISTVIEW_DATA_MORE);
					lvNewBook_foot_more.setText(R.string.load_error);
					((AppException)msg.obj).makeToast(NewBook.this);
				}
				if(lvNewBookData.size()==0){
					mLvNewBook.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					lvNewBook_foot_more.setText(R.string.load_empty);
				}
				
				lvNewBook_foot_progress.setVisibility(View.GONE);
				if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH){
					mLvNewBook.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
					mLvNewBook.setSelection(0);
				}else if(msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG){
					mLvNewBook.onRefreshComplete();
					mLvNewBook.setSelection(0);
				}
			}
		};
		
		loadLvNewBookData(1, 1, mNewBookHandler, UIHelper.LISTVIEW_ACTION_INIT);
    	
    }
    
	private void loadLvNewBookData(final int catalog, final int pageIndex, final Handler handler, final int action) {
		
		headButtonSwitch(DATA_LOAD_ING);
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;
				
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH 	|| action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				
				try {
					BookshelfList list = ((AppContext)getApplication()).getNewBook(catalog, pageIndex, isRefresh);
					msg.what = list.getPageSize();
					msg.obj = list;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;				
				handler.sendMessage(msg);
				
			}
		}.start();	
	}
}